#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This script is used to download in parallel several files using mimms.
#
# TODO
#  - add a indicator when all downloads are finished
#  - add a way to specify the output directory from the GUI
#
# @author Jean-Baptiste Fiot <hellwoxx@gmail.com>
# @version June 2011

import os, time, wx, traceback, Image, sys, subprocess

#################################################
#                  Options                      #
#################################################

OUTPUT_DIR = '/media/FIOT/Downloads'
PARALLEL_DOWNLOADS = 1


class MyFrame(wx.Frame):
  def __init__(self, zoom):
    #################################################
    #                   GUI stuff                   #
    #################################################
    
    self.zoom = zoom
    self.model = 1
    wx.Frame.__init__(self, None, -1, "[Fiot 2011] MMS List Downloader")
    self.panel = wx.Panel(self, -1)
    
    # MMS Links Input Zone
    self.inputZone = wx.TextCtrl(self.panel, id=-1, size = wx.Size(600, 500), style=wx.TE_MULTILINE)
    self.inputZone.Bind(wx.EVT_TEXT, self.OnChangeInput)
    
    # Names Input Zone
    self.inputZone2 = wx.TextCtrl(self.panel, id=-1, size = wx.Size(300, 500), style=wx.TE_MULTILINE)
    
    # Button	
    launch_img = wx.Image(os.path.join(os.path.dirname(sys.argv[0]),"GUI_pics","apply.png"), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
    self.launchButton = wx.BitmapButton(self.panel, id=-1, bitmap=launch_img)
    self.launchButton.Bind(wx.EVT_BUTTON, self.OnLaunch)
    
    # Sizer
    self.sizer = wx.FlexGridSizer(cols = 3)
    self.sizer.Add(self.inputZone,1,wx.EXPAND|wx.LEFT|wx.RIGHT,10)
    self.sizer.Add(self.inputZone2,1,wx.EXPAND|wx.LEFT|wx.RIGHT,10)
    self.sizer.Add(self.launchButton, flag = wx.ALIGN_CENTER)

    self.status = wx.StatusBar(self.panel, id = -1, name = "statusBar")

    self.vertsizer = wx.FlexGridSizer(cols = 1)
    self.vertsizer.Add(self.sizer)
    self.vertsizer.Add(self.status)
    
    border = wx.BoxSizer()
    border.Add(self.vertsizer, 0, wx.ALL, 10)
    
    self.panel.SetSizerAndFit(border)
    self.Fit()
    
    self.OnChangeInput(self)
    
    
    #################################################
    #           Content initialization              #
    #################################################
  
    if not wx.TheClipboard.IsOpened():  # may crash, otherwise
      content = wx.TextDataObject()
      wx.TheClipboard.Open()
      success = wx.TheClipboard.GetData(content)
      wx.TheClipboard.Close()
      if success:
          str = content.GetText()
          # Remove unwanted spaces and CR at the beginning and at the end
          while str[-1] == " " or str[-1] == "\n":
            str = str[0:-1]
          while str[0] == " " or str[0] == "\n":
            str = str[1:]
          # Now we check if it is 
          if 'mms://' in str:
            self.status.SetStatusText("Status: mms:// link found in the clipboard. :)")
            self.inputZone.SetValue(str)
          else:
            self.status.SetStatusText("Status: Please paste MMS links on the left. Optional: you can paste filenames on the right")
      else:
          self.status.SetStatusText("Status: There is no data in the clipboard in the required format")
    else:
      self.status.SetStatusText('Status: Sadly, the clipboard is locked')
    
    
  #################################################
  #                   Events                      #
  #################################################
  
  def OnLaunch(self, evt):
    links = self.inputZone.GetValue()
    links = links.split('\n')
    filenames = self.inputZone2.GetValue()
    filenames = filenames.split('\n')
    
    for ind in range(len(links)):
      link = links[ind]
      to_run = ['mimms', link]
      if len(filenames) > ind:
        filename = filenames[ind]
        # If the filename does not have any extension, we take it from the link
        if len(os.path.splitext(filename)) != 2 or len(os.path.splitext(filename)[-1]) != 4 or os.path.splitext(filename)[-1][0] != '.':
          filename += os.path.splitext(link)[-1]
        to_run.append(filename)
      else:
        print 'Warning: no filename for ' + link
      print 'Calling', to_run
      if PARALLEL_DOWNLOADS:
        subprocess.Popen(to_run,cwd = OUTPUT_DIR) # all downloads at the same time
      else:
        subprocess.call(to_run,cwd = OUTPUT_DIR) # one download at a time
      
      
          
  def OnChangeInput(self, evt):
    if len(self.inputZone.GetValue()) > 0:
      self.launchButton.Enable()
    else:
      self.launchButton.Disable()

class MyApp(wx.App):
    def OnInit(self):
        self.MyFrame = MyFrame(2)
        self.MyFrame.Center(wx.BOTH)
        self.MyFrame.Show()
        return True


app = MyApp(False)

# Traceback
def Myexcepthook(type, value, tb):
        lines=traceback.format_exception(type, value, tb)
        wx.MessageBox("\n".join(lines), "Traceback Error")
sys.excepthook=Myexcepthook


app.MainLoop()

